package handler

import (
	"fmt"
	"net/http"
	"time"
	"yunpan/db"
	"yunpan/store/ceph"
	"yunpan/utils"
	"github.com/gin-gonic/gin"
)

const(
	pwd_salt = "*#890"
)

// SignupHandler 注册处理
func SignupHandler(c *gin.Context) {
	// 移除HTML相关代码
	username := c.PostForm("username")
	passwd := c.PostForm("password")
	email := c.PostForm("email")

	if len(username) < 3 || len(passwd) < 5 {
		c.JSON(http.StatusBadRequest, gin.H{
			"code": 400,
			"msg": "Invalid parameter",
		})
		return
	}

	// 创建 Ceph 用户
	s3key, secret, err := ceph.CreateCephUser(username, username, email, "", "")
	if err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{
			"code": 500,
			"msg": "Failed to create Ceph user",
		})
		return
	}

	enc_passwd := utils.Sha1([]byte(passwd + pwd_salt))
	if suc := db.UserSignup(username, enc_passwd, email, s3key, secret); suc {
		c.JSON(http.StatusOK, gin.H{
			"code": 200,
			"msg": "Success",
		})
	} else {
		c.JSON(http.StatusInternalServerError, gin.H{
			"code": 500,
			"msg": "Failed to create user",
		})
	}
}

// SigninHandler 登录处理
func SigninHandler(c *gin.Context) {
	username := c.PostForm("username")
	password := c.PostForm("password")
	encPasswd := utils.Sha1([]byte(password + pwd_salt))

	// 验证用户名和密码
	if !db.UserSignin(username, encPasswd) {
		c.JSON(http.StatusUnauthorized, gin.H{
			"code": 401,
			"msg": "Invalid username or password",
		})
		return
	}

	// 生成token
	token := GenToken(username)
	if !db.UpdateToken(username, token) {
		c.JSON(http.StatusInternalServerError, gin.H{
			"code": 500,
			"msg": "Failed to generate token",
		})
		return
	}

	c.JSON(http.StatusOK, gin.H{
		"code": 200,
		"msg": "OK",
		"data": gin.H{
			"token": token,
			"username": username,
		},
	})
}

// UserInfoHandler 用户信息处理
func UserInfoHandler(c *gin.Context) {
	username := c.PostForm("username")
	user, err := db.GetUserInfo(username)
	if err != nil {
		c.JSON(http.StatusForbidden, gin.H{
			"code": 403,
			"msg": "Failed to get user info",
		})
		return
	}

	c.JSON(http.StatusOK, gin.H{
		"code": 200,
		"msg": "OK",
		"data": user,
	})
}

func GenToken(username string) string{
	//40位字符：md5(username+timestamp+token_salt)+timestamp[:8]
	ts := fmt.Sprintf("%x",time.Now().Unix())
	tokenPrefix := utils.MD5([]byte(username+ts+"_tokensalt"))
	return tokenPrefix+ts[:8]
}

func IsTokenValid(token string) bool {
	if len(token) != 40{
		return false
	}
	//先判断后八位有没有过时，再判断有没有必要去数据库查询
	return true
}